package com.dk.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dk.pojo.TPerson;
import com.dk.service.MenuService;
import com.dk.service.PersonService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

//登录与授权逻辑编写的位置
public class LoginRealm extends AuthorizingRealm {

    @Reference
    private PersonService personService;

    @Reference
    private MenuService menuService;

    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权方法");
        //给我们访问的方法授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //添加权限字符串
       /* List<String> list = new ArrayList<>();
        list.add("add");
        list.add("delete");*/
        TPerson person  =(TPerson) SecurityUtils.getSubject().getPrincipal();
        List<String> perms = menuService.selectPermsById(person.getPid());
        info.addStringPermissions(perms);
        return info;
    }

    //登录方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入认证方法");
        //获取token
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        String username = token.getUsername();
        //根据用户名查询用户这是否存在
        TPerson person = personService.getByName(username);
        if(!username.equals(person.getPname())){
            return null;
        }
        //第一个,登陆成功后,用户存放到session
        //第二个,数据库里的密码
        //第三个数据库的盐
        //第四个,登陆成功后,用户的账户名
        return new SimpleAuthenticationInfo(person,person.getPwd(), ByteSource.Util.bytes(person.getSalt()),person.getPname());
    }
}
